package www.bwsensing.com.common.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import www.bwsensing.com.common.CollectionService;
import www.bwsensing.com.common.netty.initializer.NettyUdpInitializer;
import www.bwsensing.com.common.utills.NetworkInterfaceUtil;

/**
 * @author macos-zyj
 */
@Slf4j
@Data
public class NettyUdpServerImpl implements CollectionService {

    private Integer port;

    private NettyUdpInitializer nettyUdpInitializer;

    private EventLoopGroup group = new NioEventLoopGroup();


    public NettyUdpServerImpl(Integer port, NettyUdpInitializer nettyUdpInitializer) {
        this.port = port;
        this.nettyUdpInitializer = nettyUdpInitializer;
    }

    @Override
    public void start() {
        Bootstrap udpServer = new Bootstrap();
        log.info("Udp service init!");
        try {
            udpServer.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .option(ChannelOption.SO_RCVBUF, 1024 * 1024 * 100)
                    .handler(nettyUdpInitializer);
            // 服务器绑定端口监听
            ChannelFuture channelHttp = udpServer.bind(port).sync();
            log.info("UDP服务监听端口启动成功，端口为:{}", port);
            channelHttp.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.error("UDP Service start error cause:{}",e.getMessage());
        } finally {
            // 关闭EventLoopGroup，释放掉所有资源包括创建的线程
            group.shutdownGracefully();
        }
    }

    @Override
    public void stop()  {
        group.shutdownGracefully();
        if (!NetworkInterfaceUtil.isLocalPortUsing(port)){
            log.info("UDP服务监听端口关闭成功，端口为:{}", port);
        }
    }

}
